import { createRouter, createWebHashHistory } from 'vue-router';
import type { App } from 'vue';

import { useRouteStore } from '@/store/modules/routeMenu';
import { getMenus } from '@/api/userAndAuth';
import { publicRoutes } from './route';
import { usePermissionStore } from '@/store/modules/permission';
import { useGlobalStoreWithOut } from '@/store/modules';

export const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: [...publicRoutes],
  // 是否应该禁止尾部斜杠
  strict: true,
});

// 防止首次或者刷新界面路由失效
let registerRouteFresh = true;
router.beforeEach(async (to, from, next) => {
  // 首次进来加载一次
  if (registerRouteFresh) {
    const store = useRouteStore();
    const global = useGlobalStoreWithOut();
    await global.fetchProject();
    const permStore = usePermissionStore();
    await permStore.fetchUserInfo();
    await permStore.fetchPermissionList();
    // 判读pina中有没有数据
    if (store.routeList.length < 1) {
      const res = await getMenus();
      // 设置动态路由
      store.setRouteList(res.businessMenus, router);
      //  判断首次进来有没有路径
      if (to.path == '/') {
        // 如果后端没有数据，就到404
        if (store.routeList.length < 1) {
          next({ path: '404', replace: true });
        } else {
          next({ path: store.routeList[0].path, replace: true });
        }
      } else {
        next({ ...to, replace: true });
      }
    } else {
      next();
    }
    registerRouteFresh = false;
  } else {
    next();
  }
});

export function setupRouter(app: App<Element>) {
  app.use(router);
}
